const Base = require('./base.js');
const moment = require('moment');
//积分商城
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'sort_order asc,order_time desc';
        const goodsname = this.get('coupon_name') || '';
        const category_id = this.get('category_id') || '';
        const goods_id = this.get('goods_id') || '';
        const state = this.get('state') || '';
        let seachdata = { id:['>',0]}, timesearch = {};
        if(category_id){
            seachdata['category_id'] = category_id;
        }
        if(goods_id){
            seachdata['goods_id'] = goods_id;
        }
        if (goodsname) {
            seachdata['coupon_name'] = ['like', `%${goodsname}%`];
        }
        if(state||state===0){//是否上架
            seachdata['is_delete'] = state;
        }

        const model = this.model('coupon');
        const data = await model.where(seachdata)
        .order([sortField]).page(page, size).countSelect();
         //库存，方便显示已售罄
         for(const item of data.data){
            const redeem = await this.model('coupon_user').where({coupon_id:item.id}).count();
            let acount = item.total -redeem;
            item.goods_number= acount?acount:0;//库存
        }
        return this.success(data);
    }

    async saveAction() {
        const model = this.model('coupon');
        const values = this.post();
        const coupon_value = this.post('coupon_value');
        if(parseInt(coupon_value)<=0){
            return this.fail(400,'优惠券面值必须大于零');
        }
        let id = this.post('id');
        if (id>0) {
            id=await model.where({ id: id }).update(values);
        } else {
            values['id']=0;
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateAction() {
        const model = this.model('coupon');
        const values = this.post();
        const coupon_value = this.post('coupon_value');
        if(parseInt(coupon_value)<=0){
            return this.fail(400,'优惠券面值必须大于零');
        }
        const id = this.post('id');
        let data = await model.where({id: id}).update(values);
        return this.success(data);
    }

    async readAction() {
        const model = this.model('coupon');
        const id = this.get('id');
        const data=await model.where({id: id}).find();
        return this.success(data);
    }
     /**
     *商品有效期定时上下架
     */
    async activeAction() {
        const model = this.model('coupon');
        const values = this.post();
        const id = this.post('id');
        values['is_delete'] = 0;
        let data = await model.where({id: id}).update(values);
        return this.success(data);
    }
    /**
     * 置顶
     */
    async topAction() {
        const model = this.model('coupon');
        const values = this.post();
        const id = this.post('id');
        const sort_order = this.post('sort_order');
        let data;

        try{
            await model.startTrans();
            data = await model.where({id: id}).update({sort_order:sort_order});
            await model.where({id: ['!=',id]}).update({sort_order:1-sort_order});
            await model.commit();
          }catch(e){
            await model.rollback();
            return this.fail('事务，未知错误');
          }
        return this.success(data);
    }

     /**
     * 置顶及取消置顶
     */
    async orderAction() {
        const model = this.model('coupon');
        const values = this.post();
        const id = this.post('id');
        const sort_order = this.post('sort_order');
        let data;

       if(sort_order==0){
            data = await model.where({id: id}).update({sort_order:0,order_time:parseInt(new Date().getTime() / 1000)});
          }else{
            data = await model.where({id: id}).update({sort_order:1,order_time:0});

          }
        return this.success(data);
    }


    async deleteAction() {
        const model = this.model('coupon');
        const id = this.post('id');
        let data = await model.where({ id: id }).delete();
        return this.success(data);
    }


    /**
     * 兑换统计
     */
    async exchangeStaticAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'hiolabs_coupon_user.id';
        const goodsname = this.get('coupon_name') || '';
        const category_id = this.get('category_id') || 0;
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        const status = this.get('status') || '';
        let name = this.get('name') || '';
        const buffer = Buffer.from(name);
        let nickname = buffer.toString('base64');

        let searchData = { 'hiolabs_coupon_user.is_delete':0}, timesearch = {};
        if(category_id){
            searchData['hiolabs_coupon_user.category_id'] = category_id;
        }
        if (goodsname) {
            searchData['hiolabs_coupon_user.coupon_name'] = ['like', `%${goodsname}%`];
        }
        if(status||status==='0'){
            searchData['hiolabs_coupon_user.status'] = status;
        }

        if(name){
            searchData['_complex'] = {
                'ou.nickname':['like', `%${nickname}%`],
                'ou.name':['like', `%${name}%`],
                'ou.mobile':['like', `%${name}%`],
                _logic:'or'
            };
        }
        if (begin || end) {
            if (begin) {
                timesearch['egt'] = parseInt(new Date(begin).getTime()/1000);
            }
            if (end) {
                timesearch['elt'] = parseInt(new Date(end).getTime()/1000);
            }
            searchData['hiolabs_coupon_user.addtime'] = timesearch;
        }


        const model = this.model('coupon_user');
        const data = await model.join({ table: 'user',  join: 'left', as:'ou', on: ['user_id', 'id'] }).where(searchData)
        .field('hiolabs_coupon_user.*,ou.nickname,ou.name,ou.mobile')
        .order(sortField).page(page,size).countSelect();
        for(const item of data.data){
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.nowstatus = await model.getnowStatusText(item.status,item.is_delete,item.failtime);//现状态
            item.add_time= moment.unix(item.addtime).format('YYYY-MM-DD');
            item.exchangestate='兑换成功';
        }

        return this.success(data);
    }


};